/**
 * 用于字典文本反显.
 * 例如: 存在一个user_id, 从user_list中获取user_name
 * const user_list = [ { user_id: 1, user_name: 'sperains }]
 *
 * const user_name = getDictName(user_list, 1, 'user_id', 'user_name');
 *
 * @param dictList 数据源列表
 * @param value    所查找的字段对应的值
 * @param key      数据源中用于查找的字段名
 * @param valueKey 用于反显的字段名
 * @returns string 返回列表中valueKey字段对应的值
 */
export function getDictName<T, K extends keyof T, U extends Exclude<keyof T, K>>(
  dictList: T[],
  value: T[keyof T],
  key: K,
  valueKey: U
) {
  const dict = dictList.find((item) => item[key] === value)
  if (dict) return dict[valueKey]

  return ''
}

export async function compressImage(imageFile: File, maxWidth: number): Promise<Blob> {
  return new Promise((resolve, reject) => {
    const image = new Image()
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')

    image.onload = () => {
      const width = image.width
      const height = image.height
      const ratio = maxWidth / width
      const newWidth = maxWidth
      const newHeight = height * ratio

      canvas.width = newWidth
      canvas.height = newHeight

      context?.drawImage(image, 0, 0, newWidth, newHeight)

      canvas.toBlob((blob) => {
        if (blob) resolve(blob)
        else reject(new Error('无法加载图片'))
      }, imageFile.type)
    }

    image.onerror = () => {
      reject(new Error('无法加载图片'))
    }

    image.src = URL.createObjectURL(imageFile)
  })
}

export const isEmptyRichText = (text?: string) => {
  if (!text) {
    return true
  }

  return text.replace(/<[^>]+>/g, '') === ''
}

export const getParameters = (URL: string) =>
  JSON.parse(
    `{"${decodeURI(URL.split('?')[1])
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')}"}`
  )

export const isEmptyObject = (obj: object) =>
  Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

export const uniqueArr = (arr: any[]) => [...new Set(arr)]
